<?php

namespace App\Http\Controllers\V1\Push;

use App\Http\Controllers\V1\Api\BaseController;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
use JPush\Client as JPush;
use Log;
use phpDocumentor\Reflection\Types\Array_;

class BasePushController extends BaseController
{
    /**
     * 推送接口
     * @param Array $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sendPush(Array $request){

        // 自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_NOT_FOUND,
            'errorMsg' => Response::$statusTexts[Response::HTTP_NOT_FOUND],
            'data' => array()
        );
        $user_ids = $request->get('userIDs');
        $alert = $request->get('alert');
        $extras = $request->get('extras');

        // 获取所有请求参数
        $reqParams = $request->all();

        // 验证请求参数
        $validator = $this->validatePushRequest($reqParams);
        if ($validator->fails()) {
            $rspData['errorMsg'] = $validator->errors()->toArray();
            $rspData['errorCode'] = Response::HTTP_BAD_REQUEST;
            return $this->sendResponse($rspData, $rspData['errorCode']);
        }

        //打印日志
        $monolog = Log::getMonolog();
        $monolog->popHandler();
        Log::useFiles(storage_path('logs/laravel-pushinfo.log'));
        Log::info('user_ids === ',$user_ids);

        //userids   //content
        $app_key = config('jpush.appKey');
        $app_secret = config('jpush.appSecret');
        $client = new JPush($app_key,$app_secret);

        if (empty($extras)) {
            $push_payload = $client->push()
                ->setPlatform(array('ios', 'android'))
                ->addAlias($user_ids)
                ->iosNotification($alert)
                ->androidNotification($alert)
                ->options(array(
                    // time_to_live: 表示离线消息保留时长(秒)，
                    // 推送当前用户不在线时，为该用户保留多长时间的离线消息，以便其上线时再次推送。
                    'time_to_live' => 5*24*60*60,

                    // apns_production: 表示APNs是否生产环境，
                    // True 表示推送生产环境，False 表示要推送开发环境；如果不指定则默认为推送生产环境
                    'apns_production' => false
                ));
        }else{
            $push_payload = $client->push()
                ->setPlatform(array('ios', 'android'))
                ->addAlias($user_ids)
                ->iosNotification($alert, array(
                    'extras' => $extras,
                ))
                ->androidNotification($alert, array(
                    'extras' => $extras,
                ))
                ->options(array(
                    // time_to_live: 表示离线消息保留时长(秒)，
                    // 推送当前用户不在线时，为该用户保留多长时间的离线消息，以便其上线时再次推送。
                    'time_to_live' => 5*24*60*60,

                    // apns_production: 表示APNs是否生产环境，
                    // True 表示推送生产环境，False 表示要推送开发环境；
                    //如果不指定则为推送生产环境。但注意，JPush 服务端 SDK 默认设置为推送 “开发环境”。

                    'apns_production' => false
                ));
        }

        try {
            $push_payload->send();
            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = '推送成功';
        } catch (\JPush\Exceptions\APIConnectionException $e) {
            $result['errorCode'] = Response::HTTP_BAD_REQUEST;
            $result['errorMsg'] = $e->getMessage();
        } catch (\JPush\Exceptions\APIRequestException $e) {
            $result['errorCode'] = Response::HTTP_BAD_REQUEST;
            $result['errorMsg'] = $e->getMessage();
        }
        return $this->sendResponse($result,$result['errorCode']);
    }

    /*
  |--------------------------------------------------------------------------
  | 功能函数-验证参数
  |--------------------------------------------------------------------------
  */
    /*
     * 验证新增教职工数据的请求
     * @param array $params
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validatePushRequest(array $param)
    {
        $customRules = array(
            'userIDs' => 'bail|required',
            'alert' => 'bail|required',
        );
        $customMessages =array(
            'userIDs.required' => '推送接收用户不能为空',
            'alert.required' => '推送内容不能为空',
        );
        return $this->validateRequest($param,$customRules,$customMessages);
    }
}
